import { Injectable, Logger } from '@nestjs/common';
import { Cron, Interval, SchedulerRegistry } from '@nestjs/schedule';
import { CronJob } from 'cron';

@Injectable()
export class TaskService {
  constructor(private readonly schedulerRegistry: SchedulerRegistry) {}
  private readonly logger = new Logger(TaskService.name);

  // 固定定时任务  每隔 45s
  //   @Cron('45 * * * * *', {})
  //   handleCron() {
  //     this.logger.debug('Called when the current second is 45');
  //   }

  // 固定定时任务  每隔 10s
  //   @Interval(10000)
  //   headleTimeout() {
  //     this.logger.debug('Called when the current second is 10');
  //   }

  // 创建定时任务，可调用
  TaskTest() {
    const job = new CronJob('45 * * * * *', () => {
      this.logger.debug('创建定时任务 每隔45s');
    });
    this.schedulerRegistry.addCronJob('TaskTest', job);
    job.start();
    this.logger.warn('任务开启成功');
  }
  // 关闭定时任务，可调用
  TaskTestStop() {
    const job = this.schedulerRegistry.getCronJob('TaskTest');
    job.stop();
    this.logger.warn('任务关闭成功');
  }
}
